<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Worker\Controller;
use Think\Controller;
use Common\Api\PageApi;
use Api\Logic\UserLogic;

/**
 * 后台基本控制器
 * @author derek <693472824@qq.com>
 */
class BaseController extends Controller {

    protected $rsp = array('rspCode'=>'', 'rspCont'=>'', 'rspDesc'=>'操作成功');
    
    protected $limit = '10';
    
    /**
     * 后台控制器初始化
     * @author derek <693472824@qq.com>
     */
    protected function _initialize(){
        
        $client_IP = get_client_ip(1);
        $forbidden = false;
        
        //IP禁止访问
        $forbiddenIP = S('forbidden.'.$client_IP);
        
        if($forbiddenIP){
            
            $forbidden = true;
        }else{
        
            api('Server/loadConfig');
            
            $clientInfo = S('ip.'.$client_IP);
            
            if($clientInfo){
                
                $time_diff = NOW_TIME - $clientInfo['starttime'];
                $count = $clientInfo['count'] + 1;
                
                $rate = C('MAX_ACCESS_FREQUENCY') ? C('MAX_ACCESS_FREQUENCY') : 10;
                
                //同一IP每秒请求数超越5次，则判定为攻击行为，禁止IP访问10分钟
                if(floor($count/$time_diff) > $rate){
                    
                    $prohibit_time = C('PROHIBIT_ACCESS_TIME') ? C('PROHIBIT_ACCESS_TIME') : 600;
                    
                    S('forbidden.'.$client_IP, $client_IP, $prohibit_time);
                    S('ip.'.$client_IP, NULL);
                    
                    $forbidden = true;
                }else{
                    
                    $clientInfo['count'] = $count;
                    S('ip.'.$client_IP, $clientInfo, 10);       //同一IP地址缓存10秒，避免同一IP第一次攻击并沉默很久后再发起CC攻击
                }
            }else{
                
                //IP不存在于缓存中，则缓存 IP首次访问时间、次数，并缓存 10 秒
                $clientInfo = array('starttime'=>NOW_TIME, 'count'=>1);
                S('ip.'.$client_IP, $clientInfo, 10);
            }
        }
        
        if($forbidden){
            
            $this->redirect('Public/login');
        }
    }
    
    /**
     * token 鉴权
     * @param string token 鉴权码
     * @return boolean 鉴权结果
     */
    protected function checkToken($account, $token){
        
        if(empty($account) || empty($token)){
            return false;
        }
        
        $tokenValue = S('token.'.$account);
        
        if($token === $tokenValue){
            return true;
        }else{
            return false;
        }
    }

}
